package org.esisar.controller.address;

import java.sql.SQLException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.esisar.controller.utils.SessionHelper;
import org.esisar.dao.AddressStatementCreator;
import org.esisar.dao.JDBCDAO;
import org.esisar.exceptions.AddressExistException;
import org.esisar.model.Address;
import org.esisar.model.Album;
import org.esisar.model.Model;

public class AddressUtils {

	public static JDBCDAO jdbcDao = new JDBCDAO();


	public static HttpServletRequest createAddress(HttpServletRequest req) throws SQLException, AddressExistException {

		Long  idClient= SessionHelper.getUserId(req);
		List<Address> foundAddresses = (List<Address>)(List<?>) jdbcDao.findAll(new AddressStatementCreator(), "idClient",idClient+"");

		Address address = getAddressInstance(req, idClient); 

		for (Address foundAddress : foundAddresses){
			if(foundAddress.equals(address)){
				throw new AddressExistException("Address already exists");
			}
		}
		jdbcDao.addToDB(new AddressStatementCreator(), address);

		req.setAttribute("message", "Address created");

		return req;
	}


	private static Address getAddressInstance(HttpServletRequest req, Long idClient) {

		String numero = req.getParameter("numero");
		String street = req.getParameter("street");
		String codepost = req.getParameter("codepost");
		String city = req.getParameter("city");
		String country = req.getParameter("country");

		Address address = new Address(numero,street,codepost,city,country,idClient);
		return address;
	}



}
